<?php

namespace App\Models;

use Hash;
// auth验证
use Illuminate\Foundation\Auth\User as AuthModel;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Models\User
 *
 * @method static bool|null forceDelete()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User newQuery()
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User onlyTrashed()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User query()
 * @method static bool|null restore()
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User withTrashed()
 * @method static \Illuminate\Database\Query\Builder|\App\Models\User withoutTrashed()
 * @mixin \Eloquent
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User newModelQuery()
 * @property-read \App\Models\Role $role
 */
class User extends AuthModel
{
	use Query;
	//开启软删除
	use SoftDeletes;
	protected $dates = ['deleted_at'];

	protected $guarded = ['_token', 'password_confirmation', 'online'];

	//角色 一对一
	public function role() {
		return $this->belongsTo(Role::class, 'role_id', 'id');
	}


	/**
	 * 检验用户名密码是否正确
	 * @param array $data
	 * @return bool
	 */
	public function login(array $data) {
		$username = $data['username'];
		// 查询是否存在该用户
		$userinfo = self::where('username', $username)->first();
		if (!$userinfo) return false;
		// 查询密码与登录密码是否一致
		$password = $data['password'];
		$res = Hash::check($password, $userinfo['password']);
		if (!$res) return false;
		// session保存对象
		session(['user' => $userinfo]);
		return true;
	}

	/**
	 * 注册用户加密入库
	 * @param array $data
	 * @return bool
	 */
	public function reg(array $data) {
		// 密码hash加密
		$data['password'] = Hash::make($data['password']);
		$res = self::create($data);
		if ($res) return true;
		return false;
	}
}
